/**
 * 用来放本程序特有的公共方法，util是放一般公共方法
 * @description 公共类
 * @author hhk
 * @date 2021-08-09
 */

const app = getApp();
const util = require("./util");
const requestUtil = require('./request');
const api = require('../config/api');

function getStringMonthAndDay(str) {
  str = str.replace(/-/g, '/');
  let date = new Date(str);
  return (date.getMonth() + 1) + '.' + date.getDate();
}


/**
 * 表单验证
 */
function formValidate(formData, userType) {
  if (util.isNullOrEmpty(formData.name)) {
    wx.showToast({title: '姓名不能为空',icon: 'error'})
    return false;
  }
  if (userType == 1) {
    if (util.isNullOrEmpty(formData.mobile)) {
        wx.showToast({title: '手机号不能为空', icon: 'error'})
        return false;
    }
    if (util.isNullOrEmpty(formData.position)) {
      wx.showToast({ title: '职位不能为空', icon: 'error' })
      return false;
    }
    if (util.isNullOrEmpty(formData.email)) {
        wx.showToast({title: '邮箱不能为空', icon: 'error'})
        return false;
    }
  }else {
    if (util.isNullOrEmpty(formData.phone)) {
        wx.showToast({title: '手机号不能为空', icon: 'error'})
        return false;
    }
    if (util.isNullOrEmpty(formData.companyName)) {
        wx.showToast({title: '公司名称不能为空', icon: 'error'})
        return false;
    }
  }
  return true;
}

/**
 * 上传历史访问记录
 * 
 * @params list id列表
 */
async function addVisitIdList(list) {
  let params = {
    userIds: list,
    custId: app.globalData.customInfo ? app.globalData.customInfo.id : null
  }
  let res = await requestUtil.request("POST", api.urls.addVisit, params);
  if (res.data.code != 0) {
    util.showToast(res.data.msg);
    return;
  }
  //TODO 
  return;
}

function formatVisitType(key) {
    if("total" == key) return "被访问总量";
    else if("today" == key) return "今日被访问量";
    else if("tomonth" == key) return "本月被访问量";
    else if("prevmonth" == key) return "上月被访问量";
    return "";
}

function getQueryParams (queryString) {
    // 微信扫码得到的内容进行了一次编码，所以官方要求需要进行decodeURIComponent一次
    queryString = decodeURIComponent(queryString)
    let params = {}
    if (queryString) {
      let queryArray = queryString.split('?')
      if (queryArray.length > 1) {
        let query = queryArray[1]
        let array = query.split('&')
        array.map((value) => {
          let valueArray = value.split('=')
          if (valueArray.length > 1) {
            // 还需要对value进行解码（可能涉及到在value为中文字符，在赋值到二维码前进行了encodeURI编码）
            Object.assign(params, { [valueArray[0]]: decodeURI(valueArray[1]) })
          }
        })
      }
    }
    return params
}
function formatImg(v) {
    return v.replaceAll('/profile', api.picUrl + '/profile');
}
/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性：max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉<br/>标签
 * @param html
 * @returns {void|string|*}
 */
function formatRichText(html){
    let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
        match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
        return match;
    });
    newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:6px;margin-bottom:0;"');
    return newContent;
}
function strIncludes(all, str) {
    if((',' + all + ',').indexOf(',' + str + ',') != -1) return true;
    else return false;
}
  
module.exports = {
  formValidate,
  getStringMonthAndDay,
  addVisitIdList,
  formatVisitType,
  getQueryParams,
  formatRichText,
  formatImg,
  strIncludes,
}